package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.ConanMenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.ConanMenuService;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @PackageName: com.itheima.service.impl
 * @ClassName: ConanMenuServiceImpl
 * @Author: WuKenan
 * @Date: 2019/12/14 11:22
 * @Description: //TODO
 */
@Service(interfaceClass = ConanMenuService.class)
@Transactional
public class ConanMenuServiceImpl implements ConanMenuService {

        @Autowired
        private ConanMenuDao conanMenuDao;
        @Autowired
        private UserDao userDao;
        @Autowired
        private RoleDao roleDao;

        @Override
        public List<Menu> getMenus(String username) {
            List<Menu> menuList = new ArrayList<>();//存放菜单对象,主菜单对象

            //根据用户名获取用户
            User user = userDao.findByUsername(username);
            // System.out.println(user.getId() + "---" + user);
            //获取用户拥有的角色
            Set<Role> roles = roleDao.findByUserId(user.getId());
            //遍历角色通过角色id查到该角色对菜单的权限
            for (Role role : roles) {
                // System.out.println(role.getName());
                //通过角色id获取父菜单
                List<Menu> parentList = conanMenuDao.findParentMenuByRoleId(role.getId());
                for (Menu parentMenu : parentList) {
                    //根据父菜单id查询子菜单对象
                    Integer parentMenuId = parentMenu.getId();
                    //获得子菜单对象
                    List<Menu>  childrenList = conanMenuDao.findSonMenuByRoleId(parentMenuId);
                    //把子菜单封装到父菜单中
                    parentMenu.setChildren(childrenList);

                    menuList.add(parentMenu);

                }
            }

            return menuList;
        }
}
